class Manage::FoldersController < ApplicationController
  include Security::Session::Access
  include Utils::Url
  include Utils::Text

  def index
    case request.method
    when :post
      case params[:commit]
      when "Cancel"
        redirect_to(:action => "index", :id => nil)
        return
      when "reorder"
        reorder_folder_contents
        redirect_to(:action => "index", :id => nil)
        return
      when "Create"
        @folder = Folder.new(params[:folder])
        if save_folder?
          flash[:notice] = "Folder was successfully created"
          redirect_to(:action => "index")
          return
        else
          render(:action => "index")
        end
      when "Update"
        @folder = Folder.find(params[:folder][:id])
        params[:folder].delete(:id)
        @folder.attributes=(params[:folder])
        if save_folder?
          flash[:notice] = "Folder was successfully updated"
          redirect_to(:action => "index")
          return
        else
          render(:action => "index")
        end
      when "Delete"
        @folder = Folder.find(params[:folder][:id])
        @folder.destroy
        redirect_to(:action => "index", :id => nil)
        return
      end
    else
      @folder = Folder.new
      @folder = Folder.find(params[:id]) if params[:id]
    end
  end

  def reset_menu
    session[:menu] = nil
    backurl = home_url
    backurl = session[:prevpage] if session[:prevpage] && session[:prevpage] != "/manage/folders/reset_menu"
    redirect_to(backurl)
  end

  private

    def save_folder?
      @folder.updated_by = current_updater_id
      if @folder.save
        fldr = get_parent_folder
        seq = FolderContent.get_next_seq(params[:folder_parent_id])
        FolderContent.create(:folder_id => fldr.id, :sub_folder_id => @folder.id, :seq => seq)
        return true
      end
      false
    end

    def get_parent_folder
      if empty_or_nil?(params[:folder_parent_id])
        Folder.find(:first, :conditions => "top_level is true")
      else
        Folder.find(params[:folder_parent_id].to_i)
      end
    end

    def reorder_folder_contents
      params.each{|key,value|
        if key == "folders"
          i = 1
          params[key].each{|line|
            fldr = FolderContent.find(get_id_from_param(line))
            fldr.seq = i
            fldr.save
            i += 1
          }
        end
      }
    end
end
